/**
 * @description 常用工具封装
 *
 */
import cryptoJs from 'crypto-js'
import axios from 'axios'
import { Toast } from 'vant'
import { Loading } from 'element-ui'
import { getToken } from '@/utils/auth'

/**
 * 创建时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      // 兼容处理
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 格式化时间
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * 字符串参数转对象
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

export function checkLon(lng) {
  const lonTest = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/
  if (!lonTest.test(lng)) {
    return false
  }
  return true
}

export function checkLat(lat) {
  const latTest = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/
  // var lat = $("#itemform [id='lat']").val();
  if (!latTest.test(lat)) {
    return false
  }
  return true
}
/**
 * 16进制图片转rgba
 *
 * @export
 * @param {String} hex 16进制
 * @param {String} a 透明度
 * @return {*}  rgba 字符串
 */

export function hexToRgb(hex, a) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? `rgba(${parseInt(result[1], 16)},${parseInt(result[2], 16)},${parseInt(result[3], 16)}, ${a})` : null
}

/**
 * Des加密
 * @param {String} message  需要加密的字符串(如果是对象需要转字符串)
 * @param {String} key      密钥(加密解密密钥同一个) key 后端提供 暂时用 "chengdu123"
 * @return {*}              64位格式
 */
export function encryptDes(message) {
  const key = 'chengdu123'
  const keyHex = cryptoJs.enc.Utf8.parse(key)
  const option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 }
  const encrypted = cryptoJs.DES.encrypt(message, keyHex, option)
  return encrypted.toString()
}

/**
 * Des解密
 * @param {String} message  需要解密的字符串
 * @param {String} key      密钥(加密解密密钥同一个) key
 * @return {*}              一般格式
 */
export function decryptDes(message) {
  const key = 'chengdu123'
  const keyHex = cryptoJs.enc.Utf8.parse(key)
  const option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 }
  const decrypted = cryptoJs.DES.decrypt(message, keyHex, option)
  return decrypted.toString(cryptoJs.enc.Utf8)
}
/**
 * 获取指定年份的上一年
 */
export const getAssignYearLastYear = (value) => {
  const date = new Date()
  date.setFullYear(value)
  return date.getFullYear() - 1
}

/**
 * 导出 GET方式
 * @param {String} url      导出接口地址 拼前缀'/DataExcavate'+
 * @param {Object} param    导出所需对象参数
 * @param {String} fileName 文件名称
 * @return {*}
 */
export const exportFile = (url, param, fileName) => {
  const token = getToken()
  axios
    .get(`${process.env.VUE_APP_BASE_API}` + url, {
      headers: {
        token: token
      },
      params: param,
      responseType: 'arraybuffer'
    })
    .then((response) => {
      // 创建一个blob对象
      const blob = new Blob([response.data])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      // 配置下载的文件名
      link.download = fileName
      link.click()
    })
}

// // 下载附件
// export const downloadAttachment = (param) => {
//   const token = getToken()
//   const url = '/admin/attachment/downloadAttachmentByUUID.do'
//   const downloadFile = `${process.env.VUE_APP_BASE_API}` + url
//   axios
//     .get(downloadFile, {
//       headers: {
//         token: token
//       },
//       params: param
//     })
//     .then((response) => {
//       const { data } = response
//       if (data.status && data.status === 1) {
//         Toast.fail(data.msg || 'Error')
//       } else {
//         const href = `${downloadFile}?attachUuid=${param.attachUuid}`
//         setTimeout(() => {
//           window.location.href = href
//         }, 1000)
//       }
//     })
// }
// 下载附件
export const downloadAttachment = (param) => {
  const loadingInstance = Loading.service({
    lock: true,
    text: '下载中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
    body: true
  })
  const token = getToken()
  const url = '/admin/attachment/downloadAttachmentByUUID.do'
  const downloadFile = param.attachUuid.includes('downloadAttachmentByUUID.do') ? param.attachUuid : `${process.env.VUE_APP_BASE_API}` + url
  let getObj = {}
  if (param.attachUuid.includes('downloadAttachmentByUUID.do')) {
    getObj = param.attachUuid.includes('fy.shymi.cn')
      ? {}
      : {
        headers: {
          token: token
        }
      }
  } else {
    getObj = {
      headers: {
        token: token
      },
      params: param
    }
  }
  axios.get(downloadFile, getObj).then((response) => {
    const { data } = response
    console.log(data.status)
    if (data.status && data.status === 1) {
      return Toast({
        message: data.msg,
        type: 'error',
        duration: 2 * 1000
      })
    } else if (data.status && data.status === 40) {
      return Toast({
        message: data.msg,
        type: 'error',
        duration: 2 * 1000
      })
    } else {
      const href = param.attachUuid.includes('downloadAttachmentByUUID.do') ? param.attachUuid : `${downloadFile}?attachUuid=${param.attachUuid}`
      setTimeout(() => {
        window.location.href = href
      }, 1000)
    }
  })
  loadingInstance.close()
}
// 获取快捷时间
export const getQuickTimer = (type) => {
  const startDate = new Date()
  const endDate = new Date()
  switch (type) {
    case '近一天':
      startDate.setDate(startDate.getDate() - 1)
      break
    case '近三天':
      startDate.setDate(startDate.getDate() - 3)
      break
    case '近一周':
      startDate.setDate(startDate.getDate() - 7)
      break
    case '近一月':
      startDate.setMonth(startDate.getMonth() - 1)
      break
    case '近三月':
      startDate.setMonth(startDate.getMonth() - 3)
      break
    case '近六月':
      startDate.setMonth(startDate.getMonth() - 6)
      break
    case '近一年':
      startDate.setFullYear(startDate.getFullYear() - 1)
      break
  }
  return {
    start: startDate,
    end: endDate
  }
}

// vant时间组件的选项格式化函数（van-datetime-picker）
export const timeFormatter = (type, val) => {
  if (type === 'year') {
    return val + '年'
  }
  if (type === 'month') {
    return val + '月'
  }
  if (type === 'day') {
    return val + '日'
  }
  if (type === 'hour') {
    return val + '时'
  }
  if (type === 'minute') {
    return val + '分钟'
  }
  if (type === 'second') {
    return val + '秒'
  }
  return val
}
// 将dom元素挂载到页面其他节点上 eg:el:this.refs.el1 selector:'body',则将ref属性为el1的元素挂载到body元素上
export const appendDomToRoot = (el, selector) => {
  // el 为要操作的dom元素，selector为要插入的根节点的选择器，为空的话，直接插入到body中
  var container
  if (selector) {
    container = document.querySelector(selector)
  }
  if (!container) {
    container = document.body
  }
  container.appendChild(el)
}

// 删除某个元素上的节点
export const removeDomToRoot = (el, selector) => {
  // el 为要操作的dom元素，selector为要插入的根节点的选择器，为空的话，直接插入到body中
  var container
  if (selector) {
    container = document.querySelector(selector)
  }
  if (!container) {
    container = document.body
  }
  container.removeChild(el)
}

/**
 * 按照索引排序
 * @param arr
 * @returns {*}
 * @author 赵京涛
 */
export const reverseArrayItems = (arr) => {
  return arr.map(item => {
    return item.split('').reverse().join('')
  })
}

/**
 * 评分明细合并一级指标
 * @param originalData
 * @returns {*[]}
 */
export const transformDataListMethods = (originalData) => {
  const transformedDataMap = originalData.reduce((map, item) => {
    const { classaIndexName, classaScore, ...rest } = item
    if (map.has(classaIndexName)) {
      map.get(classaIndexName).list.push(rest)
    } else {
      map.set(classaIndexName, {
        classaIndexName,
        classaScore,
        list: [rest]
      })
    }
    return map
  }, new Map())
  return Array.from(transformedDataMap.values())
}

/**
 * 根据最后一级id获取父级相关id
 * @param {String} key      最后一级id 或 code
 * @param {Object} treeData    级联下拉数据
 * @param {districtCode} type  类型
 * @return {*}
 */
export const changeDetSelect = (key, treeData, type = 'id') => {
  const arr = []
  const code = []
  const list = []
  let returnArr = []
  let returnCode = []
  let returnList = []
  let depth = 0
  function childrenEach(childrenData, depthN) {
    for (var j = 0; j < childrenData.length; j++) {
      depth = depthN // 将执行的层级赋值 到 全局层级
      arr[depthN] = childrenData[j].id
      code[depthN] = childrenData[j].code
      list[depthN] = childrenData[j]
      if (type === 'id') {
        // eslint-disable-next-line eqeqeq
        if (childrenData[j].id == key) {
          returnArr = arr.slice(0, depthN + 1) // 将目前匹配的数组，截断并保存到结果数组，
          returnCode = code.slice(0, depthN + 1)
          returnList = list.slice(0, depthN + 1)
          break
        } else {
          if (childrenData[j].subList) {
            depth++
            childrenEach(childrenData[j].subList, depth)
          }
        }
      } else if (type === 'code') {
        // eslint-disable-next-line eqeqeq
        if (childrenData[j].code == key) {
          returnArr = arr.slice(0, depthN + 1) // 将目前匹配的数组，截断并保存到结果数组，
          returnCode = code.slice(0, depthN + 1)
          returnList = list.slice(0, depthN + 1)
          break
        } else {
          if (childrenData[j].subList) {
            depth++
            childrenEach(childrenData[j].subList, depth)
          }
        }
      }
    }
    return { returnArr, returnCode, returnList }
  }
  return childrenEach(treeData, depth)
}
/**
 * 传入的文件名，获取文件类型
 * @param {String} filename
 * @returns {String} 文件类型
 */

export const getFileExtension = (fileName) => {
  const lastDotIndex = fileName.lastIndexOf('.')
  if (lastDotIndex === -1) {
    return '' // 如果文件名中没有点，则返回空字符串
  } else {
    return fileName.slice(lastDotIndex + 1)
  }
}

/**
 * 获取AQI或者水质背景色和字体色
 * @export
 * @param {*} name
 * @param {*} text
 * @return {*}
 */
export function getColor(name, text) {
  let className = ''
  switch (name) {
    case '优':
    case '1':
    case 'Ⅰ':
    case 'Ⅰ类':
      className = text === 'text' ? 'light-blue-text' : 'light-blue'
      break
    case '良':
    case '2':
    case 'Ⅱ':
    case 'Ⅱ类':
    case 'Ⅰ*':
    case 'Ⅰ*类':
      className = text === 'text' ? 'blue-text' : 'blue'
      break
    case '轻度污染':
    case '3':
    case 'Ⅲ':
    case 'Ⅲ类':
    case 'Ⅱ*':
    case 'Ⅱ*类':
      className = text === 'text' ? 'green-text' : 'green'
      break
    case '4':
    case 'Ⅳ':
    case 'Ⅳ类':
    case 'Ⅲ*':
    case 'Ⅲ*类':
      className = text === 'text' ? 'yellow-text' : 'yellow'
      break
    case '5':
    case '中度污染':
    case 'Ⅴ':
    case 'Ⅴ类':
    case 'Ⅳ*':
    case 'Ⅳ*类':
      className = text === 'text' ? 'orange-text' : 'orange'
      break
    case '6':
    case '劣Ⅴ':
    case '劣Ⅴ类':
    case 'Ⅴ*':
    case 'Ⅴ*类':
      className = text === 'text' ? 'red-text' : 'red'
      break
    case '重度污染':
      className = text === 'text' ? 'light-purple-text' : 'light-purple'
      break
    case '严重污染':
      className = text === 'text' ? 'deep-purple-text' : 'deep-purple'
      break
    default:
      className = text === 'text' ? 'gary-text' : 'gary'
      break
  }
  return className
}

/**
 * 标识转换为文字
 */
export function getFlagStr(val) {
  let str
  switch (val) {
    case 'N':
      str = '正常(测量数据正常有效)'
      break
    case 'T':
      str = '超上限(监测浓度超仪器测量上限)'
      break
    case 'L':
      str = '超下限(监测浓度超仪器下限或小于检出限)'
      break
    case 'P':
      str = '电源故障(系统电源故障)'
      break
    case 'D':
      str = '仪器故障'
      break
    case 'F':
      str = '仪器通信故障(仪器数据采集失败)'
      break
    case 'B':
      str = '仪器离线'
      break
    case 'Z':
      str = '取水点无水样(取水点没有水样或采水泵未正常上水)'
      break
    case 'S':
      str = '手工输入数据(手工输入的补测值)'
      break
    case 'M':
      str = '维护调试数据(仪器仪表处于维护期间产生的数据)'
      break
    case 'hd':
      str = '现场启动测试'
      break
  }
  return str
}

/**
 * 获取AQI或者水质背景色和字体16进制颜色
 */
export const getColor16 = (value) => {
  let color = ''
  switch (value) {
    case 1:
    case '1':
      color = '#73EFFF'
      break
    case 2:
    case '2':
      color = '#29C3EF'
      break
    case 3:
    case '3':
      color = '#63DB29'
      break
    case 4:
    case '4':
      color = '#FFEB00'
      break
    case 5:
    case '5':
      color = '#F78E29'
      break
    case 6:
    case '6':
      color = '#EF2821'
      break
  }

  return color
}

/**
 * 根据输入的值来匹配对应的数据结构
 * @param options
 * @param value
 * @returns {{}|*}
 */
export const useFindOptionByValueRecursive = (options, value) => {
  for (const option of options) {
    if (option.value === value) {
      return option
    } else if (option.children) {
      const found = useFindOptionByValueRecursive(option.children, value)
      if (found) {
        return found
      }
    }
  }
  return null
}
